﻿using System;
using System.Windows.Threading;
using TestBat.IModels.Services;
using TestBat.IViewModels.Base;
using TestBat.ServiceLocator;

namespace TestBat.ViewModels.Base
{
    public class UnsavedChangesViewModel : ViewModel, IUnsavedChangesViewModel
    {
        public UnsavedChangesViewModel()
        {
            this.unsavedChanges = false;

            this.unsavedChangesTimer = new DispatcherTimer();
            this.unsavedChangesTimer.Interval = TimeSpan.FromMilliseconds(10);
            this.unsavedChangesTimer.Tick += UnsavedChangesCallback;
            this.unsavedChangesTimer.Start();
        }

        ~UnsavedChangesViewModel()
        {
            this.unsavedChangesTimer.Stop();
        }

        public bool HasUnsavedChanges
        {
            get
            {
                return unsavedChanges;
            }
            private set
            {
                unsavedChanges = value;
                NotifyPropertyChanged(() => this.HasUnsavedChanges);
            }
        }

        private void UnsavedChangesCallback(object sender, EventArgs e)
        {
            HasUnsavedChanges = DefaultServiceLocator.Get<IUnsavedChangesService>().UnsavedChanges();
        }

        private DispatcherTimer unsavedChangesTimer;
        private bool unsavedChanges;
    }
}
